package csc.com.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import csc.com.repository.Users;
import csc.com.service.UserService;

@Controller
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/user/register", method=RequestMethod.GET)
	protected String fillRegisterForm (Model model) {
		model.addAttribute("user",new Users());
		return "registerPage";
	}
	@RequestMapping(value="/user/register", method=RequestMethod.POST)
	protected String register (@ModelAttribute("user")  @Valid Users user, BindingResult result,
			Model model) throws Exception {
		String nextPage;
		if (result.hasErrors()) {
			nextPage = "registerPage";
		} else {
			userService.addUser(user);
			nextPage = "loginPage";
		}
		return nextPage;
	}
	@RequestMapping(value="/user/login", method=RequestMethod.GET)
	protected String fillLoginForm (Model model) {
		model.addAttribute("user",new Users());
		return "loginPage";
	}
	@RequestMapping(value="/user/login", method=RequestMethod.POST)
	protected String login (@ModelAttribute("user") Users users,Model model, BindingResult result) throws Exception {
		Users user = userService.getUser(users.getLoginId(), users.getPassword());
		String nextPage;
		if (user.getLoginId() == null ) {
			model.addAttribute("error","Invalid username/password. Please try again ");
			nextPage = "loginPage";
		} else {
			nextPage = "redirect:userslist?"+"user="+user.getLoginId();
		}
		return nextPage;
	} 
	@RequestMapping(value="/user/userslist", method=RequestMethod.GET)
	protected String printUserList(Model model,@RequestParam("user") String loginId) {
		model.addAttribute("loginId", loginId);
		List<Users> userList = userService.getUsers();
		model.addAttribute("userList",userList);
		return "userListPage";
	}
}
